package syncon;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import com.google.gdata.client.Query;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.util.ServiceException;

public class FBPhoto {
	public FBPhoto() throws IOException, ServiceException {

		// Request the feed
		URL feedUrl = new URL(
				"https://www.google.com/m8/feeds/contacts/default/full");
		Query myQuery = new Query(feedUrl);
		myQuery.getMaxResults();
		ContactFeed resultFeed = Syncon.googleService.getFeed(feedUrl,
				ContactFeed.class);
		while (true) {
			for (int i = 0; i < resultFeed.getEntries().size(); i++) {
				ContactEntry entry = resultFeed.getEntries().get(i);
				fetchPhoto(entry);
			}
			if (resultFeed.getNextLink() == null) {
				break;
			}

			feedUrl = new URL(resultFeed.getNextLink().getHref());
			myQuery = new Query(feedUrl);
			myQuery.getMaxResults();
			resultFeed = Syncon.googleService.getFeed(myQuery,
					ContactFeed.class);
		}

	}

	private String fetchOneName(ContactEntry entry) {
		if (entry.hasNickname()) {
			if (entry.getNickname().hasValue()) {
				return entry.getNickname().getValue();
			}
		}
		if (entry.hasName()) {
			if (entry.getName().hasFullName()) {
				if (entry.getName().getFullName().hasValue()) {
					return entry.getName().getFullName().getValue();
				} else {
					return entry.getName().getFullName().getYomi();
				}
			} else if (entry.getName().hasGivenName()) {
				if (entry.getName().getGivenName().hasValue()) {
					return entry.getName().getGivenName().getValue();
				} else {
					return entry.getName().getGivenName().getYomi();
				}

			} else if (entry.getName().hasFamilyName()) {
				if (entry.getName().getFamilyName().hasValue()) {
					return entry.getName().getFamilyName().getValue();
				} else {
					return entry.getName().getFamilyName().getYomi();
				}
			} else if (entry.getName().hasAdditionalName()) {
				if (entry.getName().getAdditionalName().hasValue()) {
					return entry.getName().getAdditionalName().getValue();
				} else {
					return entry.getName().getAdditionalName().getYomi();
				}
			}
		}

		return "Unnamed";
	}

	private void fetchPhoto(ContactEntry entry) {
		System.out.println("Fetching Emails for " + fetchOneName(entry));

		for (Email email : entry.getEmailAddresses()) {
			System.out.println(email.getAddress());
		}
		System.out.println();
	}

}
